import csv
import json
import os

import yaml


# ----------------------
# 1. 数据读取工具函数
# ----------------------
def load_yaml_config(path):
    path = os.path.abspath(os.path.join(os.getcwd(),))+ path
    with open(path, encoding='utf-8') as f:
        return yaml.safe_load(f)

def load_csv_cases(path):
    path = os.path.abspath(os.path.join(os.getcwd(),'..' )) + path
    with open(path, newline='', encoding='utf-8') as f:
        reader = csv.DictReader(f)
        cases = []
        for row in reader:
            # 空值处理
            if not row.get("query_params", "").strip():
                row["query_params"] = "{}"
            cases.append(row)  # List[dict]
        return cases


# ----------------------
# 2. 数据预处理
# ----------------------
def process_test_case(raw_case, config):
    # 强制验证输入数据类型
    assert isinstance(raw_case, dict), f"Expected dict, got {type(raw_case)}"
    assert isinstance(config, dict), f"Expected dict, got {type(config)}"
    # 合并公共配置与用例特定配置
    case = raw_case.copy()

    # 处理 Headers：合并公共头 + 用例特定头
    headers = config['common_headers'].copy()
    headers.update({
        "Authorization": case.pop("header_Authorization"),
        "Tenant-id": case.pop("header_Tenant-id")
    })
    case['headers'] = headers

    # 处理 URL：拼接基础URL
    case['url'] = config['base_url'] + case['url']

    # 处理参数（区分 GET/POST）
    if case['method'].upper() == 'GET':
        # 转换查询参数（JSON字符串 → Dict）
        case['params'] = json.loads(case.get('query_params', '{}'))  # 新增字段
    else:
        # 转换请求体（仅 POST/PUT/PATCH 需要）
        case['json'] = json.loads(case.get('request_body', '{}'))

    # 强制转换状态码为整数
    case['expected_status'] = int(case['expected_status'])

    return case
